package chap06;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ActionEvent_demo implements ActionListener {
    private JButton jbn;
    private JCheckBox jcBox;
    private JCheckBox jcAll;
    private JTextField jtf;
    public static void main(String[] args) {
        new ActionEvent_demo();

    }
    public ActionEvent_demo(){
        init();
    }
    public void init(){
        jbn = new JButton("ok");
         jtf = new JTextField();
        jtf.setPreferredSize(new Dimension(150, 20));
        //多选
        JComboBox jcb = new JComboBox();
        jcb.addItem("广州市");
        jcb.addItem("相关市");
        jcBox = new JCheckBox("打羽毛球");
        jcAll = new JCheckBox("全选");
        JFrame frame = new JFrame("测试");
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.add(jbn);
        frame.add(jtf);
        frame.add(jcBox);
        frame.add(jcAll);
        jbn.addActionListener(this);
        jtf.addActionListener(this);
        jcb.addActionListener(this);
        jcAll.addActionListener(this);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        Object obj=e.getSource();
        if (obj == jbn) {
        String s=e.getActionCommand();
            System.out.println("按键选中 他的内容是"+this.jtf.getText());
        }
        if(obj instanceof JTextField){
            JTextField jtf = (JTextField) obj;
            System.out.println(jtf.getText()+"文本框被选中");
        }
        if (obj instanceof JCheckBox) {
            System.out.println(obj.getClass());
            JComboBox jcb=(JComboBox)obj;
            Object o=jcb.getSelectedItem();
            System.out.println(o + "被选择");
        }
        if(obj instanceof JCheckBox){
            JCheckBox jcb=(JCheckBox) obj;
            jcBox.setSelected(jcb.isSelected());
            System.out.println(jcb.isSelected());
            if (jcb.isSelected()) {
                String s=jcb.getActionCommand();
                System.out.println(s + "复选框选中了");
            }
        }
    }

}
